﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Collections;
using System.Reflection;

/// <summary>
/// Summary description for atm_Gen
/// </summary>
namespace atmGen
{
    /*************
    atm_Gen.GNModes mModes = atm_Gen.GNModes.emModesNone;
    atm_Gen.GNStates mStates = atm_Gen.GNStates.emStatesNone;
    atm_Gen.GNSubStates mSubStates = atm_Gen.GNSubStates.emSubStatesNone;
      
    atm_Gen.getState(ref mModes, ref  mStates, ref  mSubStates);

     * ****************/


    public class atm_Gen
    {
        const string CTstsScreenControl = "stsScreenControl";

        public enum GNModes
        {
            emModesNone = -1,
            emModesManagement = 0,
            emModesOperation
        }
        public enum GNStates
        {
            
            /// <summary>
            /// ยกเลิกใบคำขอ
            /// </summary>
            emStatesCancel =-1,
            emStatesNone = 0,

            /// <summary>
            /// บันทึกคำขอ
            /// </summary>
            emStatesNewReg = 1,
            /// <summary>
            /// รับเรื่อง
            /// </summary>
            emStatesGetJob = 2,
            /// <summary>
            /// วิเคราะห์
            /// </summary>
            emStatesAnalyst = 3,

            /// <summary>
            /// สร้างใบอนุมัติ
            /// </summary>
            emStatesCreateProve = 4,
            /// <summary>
            /// ตรวจผล
            /// </summary>
            emStatesProve = 5,
            /// <summary>
            /// ส่งอนุมัติ
            /// </summary>
            emStatesAuthorizePre = 6,
            /// <summary>
            /// งานส่งอนุมัติ
            /// </summary>
            emStatesAuthorize = 7,
            emStatesAuthorizePass = 8,
            emStatesAuthorizeNotPass = 9,
            /// <summary>
            /// ลงทะเบียน
            /// </summary>
            emStatesRegOper = 10,
            /// <summary>
            /// ยกเลิกการลงทะเบียน
            /// </summary>
            emStatesRegOperCancel = 11,
            /// <summary>
            /// พร้อมออกแผน
            /// </sum
            /// <summary>mary>
            emStatesPlan = 12,
            /// รอผลติดตั้ง
            /// </summary>
            emStatesPlanWaitForFinal = 13,//4
            /// <summary>
            /// ระบุข้อมูลตามแผน
            /// </summary>
            emStatesPlanSpecific = 14,
            /// <summary>
            /// ติดตั้งสมบูรณ์
            /// </summary>
            emStatesPlanFinal = 15,
            /// <summary>
            /// ปรับปรุงพื้นที่
            /// </summary>
            emStatesPlacePrep = 20,
            /// <summary>
            /// ลงผล - reserve
            /// </summary>
            emStatesUpdate = 30,
            /// งานสัญญา
            emStatesContract = 40,
            /// รอดำเนินการ
            emStatesStandBy = 122,
            emStatesPlanWaitForFinalANDUpdate= 1330


            
        }
        //1	ติดตั้งใหม่
        //2	เพิ่ม
        //3	ทดแทน
        //4	ยกเลิก
        //5	เปลี่ยนแปลง
        //6	ย้าย
        //7	บันทึกคำขอ(ร่าง)
        public enum GNSubStates
        {
            emSubStatesNone = 0,
            /// <summary>
            /// ติดตั้งใหม่
            /// </summary>
            emSubStatesNew = 1,
            /// <summary>
            /// เพิ่ม
            /// </summary>
            emSubStatesAdd = 2,
            /// <summary>
            /// ทดแทน
            /// </summary>
            emSubStatesReplace = 3,
            /// <summary>
            /// ยกเลิก
            /// </summary>
            emSubStatesCancel = 4,
            /// <summary>
            /// เปลี่ยนแปลง
            /// </summary>
            emSubStatesChange = 5,
            /// <summary>
            /// ย้าย
            /// </summary>
            emSubStatesMove = 6,
            /// <summary>
            /// บันทึกคำขอ(ร่าง)
            /// </summary>
            emSubStatesDraf = 7
        }

        public enum GNSubStatesCover
        {


            emSubStatesCoverNone = 0,
            /// <summary>
            /// รายการใบคำขอ (ร่าง)
            /// </summary>
            emSubStatesCoverDraf = 1,

            /// <summary>
            /// บันทึกคำขอเปลี่ยนแปลง
            /// </summary>
            emSubStatesCoverChange = 2
        }
        public enum stsScreenControl
        {
            mngNormal,
            oprReg,//ลงทะเบียน
            oprSummaryTab,//ติดตามสถานะงานลงทะเบียน
            oprInquiry,//ค้นหาข้อมูล'ทะเบียนเครื่องอิเล็กทรอนิกส์'
            oprPlan,//ระบุข้อมูลตามแผน-ออกแผน
            Updat,//ผลการติดตั้ง/ยกเลิกเครื่องอิเล็กทรอนิกส์
            PlacePrep,//เพิ่มงานปรับปรุง
            PlacePreprpt,//รายการงานปรับปรุง
            PlacePrepHist,//ค้นหาประวัติการปรับปรุง
            contNew,
            contMnt,
            ControlModePlan,
            ControlModeStatesUpdate,
            ContractInquiry,
            RestartState,
            operdraf,
            operplan,
            operwait,
            operupdate,
            opercomplete,
            opercancle
        }

        static string _curPageName = "";
        public atm_Gen()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static stsScreenControl procMode
        {
            get
            {
                return HttpContext.Current.Session[CTstsScreenControl] == null ? stsScreenControl.mngNormal : (stsScreenControl)HttpContext.Current.Session[CTstsScreenControl];
            }
            set
            {
                HttpContext.Current.Session[CTstsScreenControl] = value;
            }
        }

        public static bool isChange {


            get
            {
                return HttpContext.Current.Session["isChange"] == null ? false : (bool.Parse(HttpContext.Current.Session["isChange"].ToString()));
            }
            set
            {
                HttpContext.Current.Session["isChange"] = value;
            }
        }
        public static bool ReadOnlyAll
        {
            get
            {
                return HttpContext.Current.Session["ReadOnlyAll"] == null ? false : (bool.Parse(HttpContext.Current.Session["ReadOnlyAll"].ToString()));
            }
            set
            {
                HttpContext.Current.Session["ReadOnlyAll"] = value;
            }
        }

        /// <summary>
        /// ถ้า true - read from table reg  false - read from table regoper.
        /// </summary>
        public static bool NewRegIsDraft 
        {
            get
            {
                return HttpContext.Current.Session["NewRegIsDraft"] == null ? false : (bool.Parse(HttpContext.Current.Session["NewRegIsDraft"].ToString()));
            }
            set
            {
                HttpContext.Current.Session["NewRegIsDraft"] = value;
            }
        }
        public static Int64 CurT1_RegistionID
        {
            get
            {
                return HttpContext.Current.Session["CurT1_RegistionID"] == null ? -1 : (Int64.Parse(HttpContext.Current.Session["CurT1_RegistionID"].ToString()));
            }
            set
            {
                HttpContext.Current.Session["CurT1_RegistionID"] = value;
            }
        }
       

        public static bool UseTblReg()
        {
            atm_Gen.GNModes mMode = atm_Gen.GNModes.emModesNone;
            atm_Gen.GNStates mState = atm_Gen.GNStates.emStatesNone;
            atm_Gen.GNSubStates mSubState = atm_Gen.GNSubStates.emSubStatesNone;
            atm_Gen.GNSubStatesCover mSubStateCover = GNSubStatesCover.emSubStatesCoverNone;            
            atm_Gen.getState(ref mMode, ref  mState, ref  mSubState, ref mSubStateCover);
            if (mMode == GNModes.emModesOperation) { return false; }
            if (mSubStateCover == GNSubStatesCover.emSubStatesCoverDraf) { return true; }
            if (mSubState == GNSubStates.emSubStatesNew) { return true; }
            return false;
        }
        public static bool UseRegMac()
        {
            atm_Gen.GNModes mMode = atm_Gen.GNModes.emModesNone;
            atm_Gen.GNStates mState = atm_Gen.GNStates.emStatesNone;
            atm_Gen.GNSubStates mSubState = atm_Gen.GNSubStates.emSubStatesNone;
            atm_Gen.GNSubStatesCover mSubStateCover = GNSubStatesCover.emSubStatesCoverNone;
            atm_Gen.getState(ref mMode, ref  mState, ref  mSubState, ref mSubStateCover);
            if (mSubStateCover == GNSubStatesCover.emSubStatesCoverDraf) { return true; }
            if (mSubState == GNSubStates.emSubStatesNew) { return true; }
            return false;
        }
        public static int GNSubStatesToInt(GNSubStates SubStates)
        {
            return (int)SubStates;
        }
        public static string curPageName
        {
            get { return _curPageName; }
            set { _curPageName = value; }
        }
        public static GNModes Mode
        {
            get
            {
                return (GNModes)Enum.Parse(typeof(GNModes), HttpContext.Current.Session["xMode"].ToString());
            }
            set
            {
                HttpContext.Current.Session["xMode"] = Convert.ToInt16(value);
            }
        }
        public static GNStates State
        {
            get
            {
                return (GNStates)Enum.Parse(typeof(GNStates), HttpContext.Current.Session["xState"].ToString());
            }
            set
            {
                HttpContext.Current.Session["xState"] = Convert.ToInt16(value);
            }
        }
        public static GNSubStates SubState
        {
            get
            {
                return (GNSubStates)Enum.Parse(typeof(GNSubStates), HttpContext.Current.Session["xSubState"].ToString());
            }
            set
            {
                HttpContext.Current.Session["xSubState"] = Convert.ToInt16(value);
            }
        }
        public static GNSubStatesCover SubStateCover
        {
            get
            {
                return (GNSubStatesCover)Enum.Parse(typeof(GNSubStatesCover), HttpContext.Current.Session["xSubStateCover"].ToString());
            }
            set
            {
                HttpContext.Current.Session["xSubStateCover"] = Convert.ToInt16(value);
            }
        }

        public static void setState(string Mode, string State, string SubState, string SubStateCover)
        {
            setState(Convert.ToInt16(Mode), Convert.ToInt16(State), Convert.ToInt16(SubState), Convert.ToInt16(SubStateCover));
        }
        public static void setState(int Mode, int State, int SubState, int SubStateCover)
        {
            HttpContext.Current.Session["xMode"] = Mode;
            HttpContext.Current.Session["xState"] = State;
            HttpContext.Current.Session["xSubState"] = SubState;
            HttpContext.Current.Session["xSubStateCover"] = SubStateCover;
        }
        public static void setState(GNModes Mode, GNStates State, GNSubStates SubState, GNSubStatesCover SubStateCover)
        {
            HttpContext.Current.Session["xMode"] = Convert.ToInt16(Mode);
            HttpContext.Current.Session["xState"] = Convert.ToInt16(State);
            HttpContext.Current.Session["xSubState"] = Convert.ToInt16(SubState);
            HttpContext.Current.Session["xSubStateCover"] = Convert.ToInt16(SubStateCover);
        }
        public static void getState(ref GNModes Mode, ref  GNStates State, ref GNSubStates SubState, ref GNSubStatesCover SubStateCover)
        {
            Mode = (GNModes)int.Parse(HttpContext.Current.Session["xMode"].ToString());
            State = (GNStates)int.Parse(HttpContext.Current.Session["xState"].ToString());
            SubState = (GNSubStates)int.Parse(HttpContext.Current.Session["xSubState"].ToString());
            SubStateCover = (GNSubStatesCover)int.Parse(HttpContext.Current.Session["xSubStateCover"].ToString());
        }
        /// <summary>
        /// Receives string and returns the string with its letters reversed.
        /// </summary>
        public static string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

        /// <summary>
        /// ///////////////////////////////////////////////////
        /// </summary>
        private void SetPage()
        {
            atm_Gen.GNModes xMode = atm_Gen.GNModes.emModesNone;
            atm_Gen.GNStates xState = atm_Gen.GNStates.emStatesNone;
            atm_Gen.GNSubStates xSubState = atm_Gen.GNSubStates.emSubStatesNone;
            atm_Gen.GNSubStatesCover xSubStateCover = GNSubStatesCover.emSubStatesCoverNone;
            atm_Gen.getState(ref xMode, ref  xState, ref  xSubState, ref xSubStateCover);

            switch (xMode)
            {
                case atm_Gen.GNModes.emModesManagement:
                    SetPageManagement(xState, xSubState);
                    break;
                case atm_Gen.GNModes.emModesOperation:
                    SetPageOperation(xState, xSubState);
                    break;
            }
        }
        private void SetPageManagement(atm_Gen.GNStates xState, atm_Gen.GNSubStates xSubState)
        {
            switch (xState)
            {
                case atm_Gen.GNStates.emStatesNewReg:
                    break;
                case atm_Gen.GNStates.emStatesGetJob:
                    break;
                case atm_Gen.GNStates.emStatesAnalyst:
                    break;
                case atm_Gen.GNStates.emStatesCreateProve://สร้างใบอนุมัติ
                    break;
                case atm_Gen.GNStates.emStatesProve:
                    break;
                case atm_Gen.GNStates.emStatesAuthorize:
                    break;
                case atm_Gen.GNStates.emStatesAuthorizePass:
                    break;
                case atm_Gen.GNStates.emStatesAuthorizeNotPass:
                    break;
                case atm_Gen.GNStates.emStatesRegOper:
                    break;
                case atm_Gen.GNStates.emStatesPlacePrep:
                    break;
                case atm_Gen.GNStates.emStatesPlan:
                    break;
                case atm_Gen.GNStates.emStatesUpdate:
                    break;
                case atm_Gen.GNStates.emStatesContract://งานสัญญา
                    break;
            }
        }
        private void SetPageOperation(atm_Gen.GNStates xState, atm_Gen.GNSubStates xSubState)
        {
            switch (xState)
            {
                case atm_Gen.GNStates.emStatesNewReg://บันทึกคำขอ
                    break;
                case atm_Gen.GNStates.emStatesGetJob://รับเรื่อง
                    break;
                case atm_Gen.GNStates.emStatesAnalyst://วิเคราะห์
                    break;
                case atm_Gen.GNStates.emStatesCreateProve://สร้างใบอนุมัติ
                    break;
                case atm_Gen.GNStates.emStatesProve://ตรวจผล
                    break;
                case atm_Gen.GNStates.emStatesAuthorizePre://ส่งอนุมัติ
                    break;
                case atm_Gen.GNStates.emStatesAuthorize://งานส่งอนุมัติ
                    break;
                case atm_Gen.GNStates.emStatesAuthorizePass:
                    break;
                case atm_Gen.GNStates.emStatesAuthorizeNotPass:
                    break;
                case atm_Gen.GNStates.emStatesRegOper://ลงทะเบียน
                    break;
                case atm_Gen.GNStates.emStatesRegOperCancel://ยกเลิกการลงทะเบียน
                    break;
                case atm_Gen.GNStates.emStatesPlan://พร้อมออกแผน
                    break;
                case atm_Gen.GNStates.emStatesPlanWaitForFinal://รอผลติดตั้ง
                    break;
                case atm_Gen.GNStates.emStatesPlanSpecific://ระบุข้อมูลตามแผน
                    break;
                case atm_Gen.GNStates.emStatesUpdate://ลงผล - reserve
                    break;
                case atm_Gen.GNStates.emStatesPlanFinal://ติดตั้งสมบูรณ์
                    break;
                case atm_Gen.GNStates.emStatesPlacePrep://ปรับปรุงพื้นที่
                    break;
                case atm_Gen.GNStates.emStatesContract://งานสัญญา
                    break;
                default:
                    break;
            }

        }
        public static atm_Gen.GNStates GetNextState()
        {
            return GetStateForword(State, true);
        }
        public static atm_Gen.GNStates GetNextState(atm_Gen.GNStates CurState)
        {
            return GetStateForword(CurState, true);
        }
        public static atm_Gen.GNStates GetPrevState()
        {
            return GetStateForword(State,false);
        }
        public static atm_Gen.GNStates GetPrevState(atm_Gen.GNStates CurState)
        {
            return GetStateForword(State, false);
        }
        public static atm_Gen.GNStates GetStateForword(atm_Gen.GNStates CurState, bool Forword)
        {
            atm_Gen.GNStates[] States = { GNStates.emStatesNewReg, GNStates.emStatesGetJob, GNStates.emStatesAnalyst
                                        ,GNStates.emStatesCreateProve,GNStates.emStatesProve,GNStates.emStatesAuthorizePre
                                        ,GNStates.emStatesAuthorize,GNStates.emStatesRegOper,GNStates.emStatesPlacePrep
                                        ,GNStates.emStatesPlan,GNStates.emStatesPlanWaitForFinal,GNStates.emStatesPlanSpecific
                                        ,GNStates.emStatesPlanFinal,GNStates.emStatesUpdate,GNStates.emStatesContract};
            int i = Array.IndexOf(States, CurState);
            if (i < States.Length)
            {
                if (Forword) { return States[i + 1]; }
                else {return States[(i - 1)<0?0:(i-1) ]; }
            }
            return GNStates.emStatesNone;
        }
        public static string SubStateText(GNSubStates SubState)
        {
            string txt = "";
            switch (SubState)
            {
                case GNSubStates.emSubStatesAdd:
                    txt = "เพิ่ม";
                    break;
                case GNSubStates.emSubStatesCancel:
                    txt = "ยกเลิก";
                    break;
                case GNSubStates.emSubStatesChange:
                    txt = "เปลี่ยนแปลง";
                    break;
                case GNSubStates.emSubStatesDraf:
                    txt = "บันทึกคำขอ(ร่าง)";
                    break;
                case GNSubStates.emSubStatesMove:
                    txt = "ย้าย";
                    break;
                case GNSubStates.emSubStatesNew:
                    txt = "ติดตั้งใหม่";
                    break;
                case GNSubStates.emSubStatesReplace:
                    txt = "ทดแทน";
                    break;
            }
            return txt;
        }
        public static string HeadStateCaption()
        {
            return HeadStateCaption(atm_Gen.State);
        }
        public static string HeadStateCaption(atm_Gen.GNStates mStates)
        {
            //string head2 = "";
            string[] arrHead = "บันทึกคำขอ,รับเรื่อง,งานวิเคราะห์,สร้างใบอนุมัติ,ตรวจผล,ส่งอนุมัติ,งานอนุมัติ,ลงทะเบียน,ปรับปรุงพื้นที่,ออกแผน,รอผลติดตั้ง,ระบุข้อมูลตามแผน,ติดตั้งสมบูรณ์,ลงผลติดตั้ง,งานสัญญา".Split(',');
            //บันทึกคำขอ	รับเรื่อง งานวิเคราะห์	สร้างใบอนุมัติ	ตรวจผล	ส่งอนุมัติ	งานอนุมัติ	ลงทะเบียน	ปรับปรุงพื้นที่ ออกแผน	ลงผลติดตั้ง	งานสัญญา
            atm_Gen.GNStates[] States = { GNStates.emStatesNewReg, GNStates.emStatesGetJob, GNStates.emStatesAnalyst
                                        ,GNStates.emStatesCreateProve,GNStates.emStatesProve,GNStates.emStatesAuthorizePre
                                        ,GNStates.emStatesAuthorize,GNStates.emStatesRegOper,GNStates.emStatesPlacePrep
                                        ,GNStates.emStatesPlan,GNStates.emStatesPlanWaitForFinal,GNStates.emStatesPlanSpecific
                                        ,GNStates.emStatesPlanFinal,GNStates.emStatesUpdate,GNStates.emStatesContract};
            int i = Array.IndexOf(States, mStates);
            if (i < States.Length) { return arrHead[i]; }
            return "";
          
        }
        public static string HeadCaption()
        {
            atm_Gen.GNModes mModes = atm_Gen.GNModes.emModesNone;
            atm_Gen.GNStates mStates = atm_Gen.GNStates.emStatesNone;
            atm_Gen.GNSubStates mSubStates = atm_Gen.GNSubStates.emSubStatesNone;
            atm_Gen.GNSubStatesCover mSubStatesCover = GNSubStatesCover.emSubStatesCoverNone;

            atm_Gen.getState(ref mModes, ref  mStates, ref  mSubStates, ref mSubStatesCover);
            Boolean setlk2value = true;
            string head1 = "", head2 = "", head3 = "";

            switch (mModes)
            {
                case atm_Gen.GNModes.emModesManagement:
                    head1 = "งานอนุมัติ";
                    break;
                case atm_Gen.GNModes.emModesOperation:
                    head1 = "บริหารเครือข่ายฯ";
                    break;
            }
            head2 = HeadStateCaption(mStates);
            if (setlk2value)
            {
                switch (mSubStates)
                {
                    case atm_Gen.GNSubStates.emSubStatesNew:
                        head3 = "จุดติดตั้งใหม่";
                        break;
                    case atm_Gen.GNSubStates.emSubStatesAdd:
                        head3 = "จุดติดตั้ง เพิ่ม";
                        break;
                    case atm_Gen.GNSubStates.emSubStatesReplace:
                        head3 = "จุดติดตั้ง ทดแทน";
                        break;
                    case atm_Gen.GNSubStates.emSubStatesCancel:
                        head3 = "ยกเลิกจุดติดตั้ง ";
                        break;
                    case atm_Gen.GNSubStates.emSubStatesMove:
                        head3 = "ขอย้ายจุดติดตั้ง";
                        break;
                    //case atm_Gen.GNSubStates.emSubStatesDraf:
                    //    head3 = "รายการใบคำขอ (ร่าง)";
                    //    break;

                }
            }
            return head1 + " :: " + head2 + "-" + head3;
        }
        public static string LastLoadedControl
        {
            get
            {
                //return ViewState["LastLoaded"] as string;
                // if HttpContext.Current.Session["LastControl"] == null then ""
                return (string)(HttpContext.Current.Session["LastControl"] ?? "");
            }
            set
            {
                //ViewState["LastLoaded"] = value;
                HttpContext.Current.Session["LastControl"] = value;
            }
        }
        public static void ClearLoadControl()
        {
            HttpContext.Current.Session["PrevLoadedControl"] = null;
            HttpContext.Current.Session["PrevParams"] = null;
        }
        public static void LoadPrevControl(Page thispage)
        {
            List<string> ls = (List<string>)HttpContext.Current.Session["PrevLoadedControl"];
            if (ls.Count < 2) { return; }
            LoadControlToPage(thispage, PrevLoadedControl, PrevParams);
            if (ls.Count > 1) { ls.RemoveAt(ls.Count - 1); }
            if (ls.Count > 1) { ls.RemoveAt(ls.Count - 1); }
            HttpContext.Current.Session["PrevLoadedControl"] = ls;
            List<object[]> pls = (List<object[]>)HttpContext.Current.Session["PrevParams"];
            if (pls.Count > 1) { pls.RemoveAt(pls.Count - 1); }
            if (pls.Count > 1) { pls.RemoveAt(pls.Count - 1); }
            HttpContext.Current.Session["PrevParams"] = pls;
        }
        public static string PrevLoadedControl
        {
            get
            {
                if (HttpContext.Current.Session["PrevLoadedControl"] == null)
                {
                    HttpContext.Current.Session["PrevLoadedControl"] = new List<string>();
                }
                List<string> ls = (List<string>)HttpContext.Current.Session["PrevLoadedControl"];
                if (ls.Count < 1) { ls.Add(""); }
                return ls[ls.Count - 1];
            }
            set
            {
                if (HttpContext.Current.Session["PrevLoadedControl"] == null)
                {
                    HttpContext.Current.Session["PrevLoadedControl"] = new List<string>();
                }
                List<string> ls = (List<string>)HttpContext.Current.Session["PrevLoadedControl"];
                if (ls.Count < 1) { ls.Add(""); }
                ls.Add(value);
                HttpContext.Current.Session["PrevLoadedControl"] = ls;
            }
        }
        public static object[] PrevParams
        {
            get
            {
                if (HttpContext.Current.Session["PrevParams"] == null)
                {
                    HttpContext.Current.Session["PrevParams"] = new List<object[]>();
                }
                List<object[]> ls = (List<object[]>)HttpContext.Current.Session["PrevParams"];
                if (ls.Count < 1) { ls.Add(null); }
                return ls[ls.Count - 1];
            }
            set
            {
                if (HttpContext.Current.Session["PrevParams"] == null)
                {
                    HttpContext.Current.Session["PrevParams"] = new List<object[]>();
                }
                List<object[]> ls = (List<object[]>)HttpContext.Current.Session["PrevParams"];
                if (ls.Count < 1) { ls.Add(null); }
                ls.Add(value);
                HttpContext.Current.Session["PrevParams"] = ls;
            }
        }

        private static void LoadUserControl()
        {

        }
        public static UserControl LoadControl(Page thispage, string UserControlPath, params object[] constructorParameters)
        {
            List<Type> constParamTypes = new List<Type>();
            foreach (object constParam in constructorParameters)
            {
                constParamTypes.Add(constParam.GetType());
            }


            UserControl ctl = thispage.LoadControl(UserControlPath) as UserControl;

            // Find the relevant constructor
            ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

            //And then call the relevant constructor
            if (constructor == null)
            {
                throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
            }
            else
            {
                constructor.Invoke(ctl, constructorParameters);
            }

            // Finally return the fully initialized UC
            return ctl;
        }

        public static void LoadCtrlPage(Page thispage, string WUCPageName)
        {
            ParameterCollection FindParams = null;
            LoadCtrlPage(thispage, WUCPageName, FindParams);
        }
        public static Control LoadCtrlPage(Page thispage, string WUCPageName, params object[] constructorParameters)
        {
            return LoadCtrlPage(thispage, WUCPageName, null, constructorParameters);
        }
        public static Control LoadCtrlPage(Page thispage, string WUCPageName, ParameterCollection FindParams)
        {
            return LoadCtrlPage(thispage, WUCPageName, FindParams, null);
        }
        public static Control LoadCtrlPage(Page thispage, string WUCPageName, ParameterCollection FindParams, params object[] constructorParameters)
        {
            if (string.IsNullOrEmpty(WUCPageName) || thispage==null)
            {
                return null;
            }
            UserControl uc = null;
            //MasterPage mp = (MasterPage)this.Master;
            if (WUCPageName.IndexOf('/') < 0)
            {
                WUCPageName = "~/Controls/" + WUCPageName;
            }
            //if (thispage.Request.RequestType.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                if (WUCPageName != LastLoadedControl)
                {
                    PrevLoadedControl = LastLoadedControl;
                    PrevParams = constructorParameters;
                }
                LastLoadedControl = WUCPageName;
                if (WUCPageName.IndexOf("aspx", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    LastLoadedControl = WUCPageName;
                    //thispage.Master.Server.Transfer(WUCPageName);
                    Util.jsRedirect(thispage, WUCPageName);//.Replace("~/", ""));
                    return null;
                }
                try
                {
                    if (constructorParameters != null)
                    {
                        uc = LoadControl(thispage, WUCPageName, constructorParameters) as UserControl;
                    }
                    else
                    {
                        uc = LoadControl(thispage, WUCPageName) as UserControl;
                    }
                }
                catch (Exception ex)
                {
                    //throw ex;
                    Util.jsAlert(thispage, ex);
                }

                if (uc != null)
                {
                    Control defPHL = (Control)SearchControl(thispage.Master, "defPHL");
                    //Dynamically loaded user control events not firing on first click
                    //Fixed:add-> uc.ID = "wcid01";
                    uc.ID = uc.GetType().ToString().ToLower().Replace("asp.controls_wc_atm_", "").Replace("ascx", "C").Replace("_", "");// "wcid01";
                    try
                    {
                        if (FindParams != null)
                        {
                            //check: if web control support IContractControl
                            if (uc.GetType().GetInterface("IContractControl") != null)
                            {
                                ((IContractControl)uc).FindParms = FindParams;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //throw ex;
                        Util.jsAlert(thispage, ex);
                    }

                    //try
                    //{
                    //    ((IContractControl)uc).GridDataBindA("", "");
                    //}
                    //catch (Exception ex)
                    //{
                    //    //throw ex;
                    //    SDS_Util.jsAlert(thispage, ex);
                    //}

                    int cnt = defPHL.Controls.Count;
                    for (int i = 0; i < cnt; i++)
                    {
                        defPHL.Controls[i].EnableViewState = false;
                        //defPHL.Controls[i].Dispose();

                        ////                    defPHL.Controls[i].EnableViewState = false;
                        //defPHL.Controls.RemoveAt(0);//.Clear();
                    }
                    //clear view state
                    //HtmlInputHidden ws = (HtmlInputHidden)defPHL.FindControl("__VIEWSTATE");
                    //if (ws != null) { ws.Value = ""; }
                    defPHL.Controls.Clear();

                    // id="__VIEWSTATE"
                    //Boolean vst = uc.EnableViewState;
                    //uc.EnableViewState = false;
                    try
                    {
                        defPHL.Controls.Add(uc);
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                        //defPHL.Controls.Add(uc);
                    }
                    //uc.EnableViewState = vst;
                }
                Label mpLabel = (Label)thispage.Master.FindControl("lbscnname");
                if (mpLabel != null)
                {

                    mpLabel.Text = string.IsNullOrEmpty(atm_Gen.curPageName) ? "GEN000" : atm_Gen.curPageName;
                    mpLabel.ToolTip = System.IO.Path.GetFileName(WUCPageName);
                }
            }
            return uc;
        }
        public static Control LoadControlToPage(Page thispage, string WUCPageName)
        {
            return LoadControlToPage(thispage, WUCPageName, null, null);
        }
        public static Control LoadControlToPage(Page thispage, string WUCPageName, params object[] constructorParameters)
        {
            return LoadControlToPage(thispage, WUCPageName, null, constructorParameters);
        }
        public static Control LoadControlToPage(Page thispage, string WUCPageName, ParameterCollection FindParams)
        {
            return LoadControlToPage(thispage, WUCPageName, FindParams, null);
        }

        public static Control LoadControlToPage(Page thispage, string WUCPageName, ParameterCollection FindParams, params object[] constructorParameter)
        {
            if (string.IsNullOrEmpty(WUCPageName))
            {
                return null;
            }
            Control uc = null;
            thispage = thispage.Master.Page;
            //set default
            if (WUCPageName.IndexOf('/') < 0)
            {
                WUCPageName = "~/Controls/" + WUCPageName;
            }
            uc = LoadCtrlPage(thispage, WUCPageName, FindParams);
            UpdatePanel UpdatePanel1 = (UpdatePanel)atm_Gen.SearchControl(thispage, "UpdatePanel1");
            if (UpdatePanel1 != null)
            {
                UpdatePanel1.Update();
            }
            return uc;

        }
        public static Control SearchControl(Control root, string id)
        {
            if (root == null) { return null; }
            if (root.ID == id)
            {
                return root;
            }

            foreach (Control c in root.Controls)
            {
                Control t = SearchControl(c, id);
                if (t != null)
                {
                    return t;
                }
            }

            return null;
        }

        public static DataControlFieldCell GetCellByBoundFieldName(GridViewRow row, string fieldName)
        {
            foreach (DataControlFieldCell cell in row.Cells)
            {
                BoundField bf = cell.ContainingField as BoundField;
                if (bf != null)
                {
                    if (bf.DataField == fieldName)
                    {
                        return cell;
                    }
                }
            }
            return null;
        }

        public static int GetColumnIndex(GridView grid, string colName)
        {
            int intCount = 0;
            foreach (DataColumn col in grid.Columns)
            {
                if (col.ColumnName.ToLower().Trim() == colName.ToLower().Trim())
                {
                    return intCount;
                }
                intCount++;
            }
            return -1;

        }

        public static userLogin AppUser
        {
            get
            {
                if (HttpContext.Current.Session["AppUser"] == null)
                {
                    HttpContext.Current.Session["AppUser"] = new userLogin();
                }
                return (userLogin)HttpContext.Current.Session["AppUser"];
            }
            set { HttpContext.Current.Session["AppUser"] = value; }
        }
    }
    #region class UserPermission
    /// <summary>
    /// Sample :
    ///            atm_Gen.AppUser.Permission.setDataRight(user[0].Dataright);
    ///            atmGen.UserPermission.operTabAcc operTabAcc = atm_Gen.AppUser.Permission.getAccessAllTab();
    ///            atmGen.UserPermission.TabAcc TabAcc = atm_Gen.AppUser.Permission.getAccessAllTab(atm_Gen.GNStates.emStatesNewReg);
    ///            atmGen.UserPermission.PrintSendAcc PrintSendAcc = atm_Gen.AppUser.Permission.getPrintSendAcc();
    ///            bool tab1 = TabAcc.Tab(UserPermission.TabAccess.Tab1,UserPermission.Access.Read);
    ///            bool[] tabs = TabAcc.Tabs(UserPermission.Access.Read);
    ///            bool opertab1 = operTabAcc.Tab(UserPermission.operTabAccess.Install,UserPermission.Access.Read);
    ///            bool[] opertabs = operTabAcc.Tabs(UserPermission.Access.Read);
    ///            bool Plan = opertabs[(int)UserPermission.operTabAccess.Plan];
    /// </summary>
    public class UserPermission
    {
        public enum Access
        {
            Read = 0,
            Add,
            Update,
            Delete
        }
        //	แถบงานพื้นที่จุดติดตั้ง	แถบงานป้าย	แถบรูปภาพ	แถบพิกัดจุดติดตั้ง	งานออกแผน	งานลงผลติดตั้ง	งานสัญญา
        public enum operTabAccess
        {
            regTabMin = 0,
            /// <summary>
            /// แถบงานพื้นที่จุดติดตั้ง
            /// </summary>
            Install,// = regTabMin,
            /// <summary>
            /// แถบงานป้าย
            /// </summary>
            Board,
            /// <summary>
            /// แถบรูปภาพ	
            /// </summary>
            Picture,
            /// <summary>
            /// แถบพิกัดจุดติดตั้ง
            /// </summary>
            GISLoc,
            /// <summary>
            /// งานออกแผน
            /// </summary>
            Plan,
            /// <summary>
            /// งานลงผลติดตั้ง
            /// </summary>
            Update,
            /// <summary>
            /// งานสัญญา
            /// </summary>
            Contract,
            regTabMax = Contract
        }
        public enum TabAccess
        {
            TabMin = 0,
            Tab1,// = TabMin,
            Tab2,
            Tab3,
            Tab4,
            Tab5,
            Tab6,
            Tab7,
            TabMax = Tab7
        }
        //ตัวอย่างพิมพ์	พิมพ์	ยกเลิก	ส่งกลับ	บันทึก	ส่งเรือง
        public enum PrintSendAllow
        {
            Preview = 0,
            Print,
            Cancel,
            SendBack,
            saveDraft,
            Send
        }
        public class PrintSendAcc
        {
            
            string[] _dataTabs = null;
            public PrintSendAcc()
            {
            }
            public string[] dataTabs
            {
                get { return _dataTabs; }
                set { _dataTabs = value; }
            }
            public bool Access(PrintSendAllow access)
            {
                int accessint = (int)access;
                if (accessint >= dataTabs.Length) { return false; }
                if (_dataTabs == null) { return false; }
                char[] acc = dataTabs[0].ToCharArray();
                return (acc[accessint] == '1');
            }
        }
        public class TabAcc
        {

            string[] _dataTabs = null;
            public TabAcc()
            {
            }
            public string[] dataTabs
            {
                get { return _dataTabs; }
                set { _dataTabs = value; }
            }
            public bool Tab( TabAccess tab,Access access)
            {
                int tabint = (int)tab;
                int accessint = (int)access;
                if (dataTabs == null) { return false; }
                if (accessint >= dataTabs.Length) { return false; }
                char[] acc = dataTabs[accessint].ToCharArray();
                return (acc[tabint] == '1');
            }
            public bool[] Tabs(Access access)
            {
                
                List<bool> alltab = new List<bool>();
                int accessint = (int)access;
                //if (accessint >= dataTabs.Length) { return false; }
                foreach (TabAccess item in Enum.GetValues(typeof(TabAccess)))
                {
                    char[] acc = "0000000000".ToCharArray();
                    if (dataTabs != null)
                    {
                        acc = dataTabs[accessint].ToCharArray();
                    }
                    alltab.Add(acc[(int)item] == '1');
                }
                return alltab.ToArray();
            }

        }
        public class operTabAcc
        {

            string[] _dataTabs = null;
            public operTabAcc()
            {
            }
            public string[] dataTabs
            {
                get { return _dataTabs; }
                set { _dataTabs = value; }
            }
            public bool Tab(operTabAccess tab, Access access)
            {
                int tabint = (int)tab;
                int accessint = (int)access;
                if (dataTabs == null) { return false; }
                if (accessint >= dataTabs.Length) { return false; }
                char[] acc = dataTabs[accessint].ToCharArray();
                return (acc[tabint] == '1');
            }
            public bool[] Tabs(Access access)
            {
                List<bool> alltab = new List<bool>();
                int accessint = (int)access;
                //if (accessint >= dataTabs.Length) { return false; }
                foreach (operTabAccess item in Enum.GetValues(typeof(operTabAccess)))
                {
                    char[] acc = "0000000000".ToCharArray();
                    if (dataTabs != null)
                    {
                        acc = dataTabs[accessint].ToCharArray();
                    }

                   // char[] acc = dataTabs[accessint].ToCharArray();
                    alltab.Add(acc[(int)item] == '1');
                }
                return alltab.ToArray();
            }

        }
        #region <properties>
        private string menu;
        private string[] submenu;
        private string[] screenctrl;
        private string datactrl;
        private Hashtable DataRight = new Hashtable();

        //type, xxT111,1111|111,111|..#xxT111,1111|111,111|..#xxT111,1111|111,111|..#xxT111,1111|111,111|..
        #endregion
        public UserPermission()
        {
        }
        public UserPermission(string Menu, string[] SubMenu, string[] ScreenCtrl, string DataCtrl)
        {
            menu = Menu;
            submenu = SubMenu;
            screenctrl = ScreenCtrl;
            datactrl = DataCtrl;
            setDataRight(datactrl);
        }
        public void setDataRight(string dataRight)
        {
            if (string.IsNullOrEmpty(dataRight)) { return; }
            Hashtable tbReg = new Hashtable();
            string[] grddatas = dataRight.Split('|');
            foreach (string grData in grddatas)
            {
                string[] datas = (grData + "T").Split('T');
                if (string.IsNullOrEmpty(datas[0]) || string.IsNullOrEmpty(datas[1])) { continue; }
                if (int.Parse(datas[0]) > 0)
                {
                    tbReg.Add(datas[0], datas[1]);
                }
            }
            DataRight = tbReg;
        }

        #region <Property accessors>
        public string Menu
        {
            get { return menu; }
            set { menu = value; }
        }
        public string[] SubMenu
        {
            get { return submenu; }
            set { submenu = value; }
        }
        public string[] ScreenCtrl
        {
            get { return screenctrl; }
            set { screenctrl = value; }
        }
        public string DataCtrl
        {
            get { return datactrl; }
            set { datactrl = value; }
        }
        /// <summary>
        /// //type, xxT111,1111|111,111|..#xxT111,1111|111,111|..#88T111,1111|111,111|..#99T111,1111|111,111|..
        /// </summary>
        /// <param name="State"></param>
        /// <param name="tab"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public bool AccessTab(atm_Gen.GNStates State, Access access, TabAccess tab)
        {
            string key = ((int)State).ToString();
            if (!this.DataRight.ContainsKey(key)) { return false; }
            if (tab< TabAccess.TabMin || tab > TabAccess.TabMax) { return false;}
            string[] dataTabs = this.DataRight[key].ToString().Split(',');
            int tabint = (int)tab;
            int accessint = (int)access;
            if (accessint >= dataTabs.Length) { return false; }
            char[] acc = dataTabs[accessint].ToCharArray();
            return (acc[tabint]=='1');
        }
        public operTabAcc getAccessAllTab()
        {
            operTabAcc tabs = new operTabAcc();

            if (!this.DataRight.ContainsKey("88")) { return tabs; }
            tabs.dataTabs = this.DataRight["88"].ToString().Split(',');
            return tabs;
        }
        public TabAcc getAccessAllTab(atm_Gen.GNStates State)
        {
            TabAcc tabs = new TabAcc();

            string key = ((int)State).ToString();
            if (!this.DataRight.ContainsKey(key)) { return tabs; }
            tabs.dataTabs = this.DataRight[key].ToString().Split(',');
            return tabs;
        }
        public PrintSendAcc getPrintSendAcc()
        {
            PrintSendAcc tabs = new PrintSendAcc();

            if (!this.DataRight.ContainsKey("99")) { return tabs; }
            tabs.dataTabs = this.DataRight["99"].ToString().Split(',');
            return tabs;
        }
        
        #endregion
    }
    #endregion class UserPermission

    #region class userLogin
    public class userLogin
    {
        #region <properties>
        private string loginname, fullname;
        private int userid, level;
        private DateTime logindatetime = DateTime.MinValue;
        private string department;
        private bool islogin;
        private bool _IsOperUser;
        private UserPermission permission = new UserPermission();
        #endregion
        public userLogin()
        {
        }
        public userLogin(string Fullname, string LoginName, int UserID, int Level, DateTime LoginDateTime, string Department, bool IsLogin, UserPermission Permission)
        {
            fullname = Fullname;
            loginname = LoginName;
            userid = UserID;
            level = Level;
            logindatetime = LoginDateTime;
            department = Department;
            islogin = IsLogin;
            permission = Permission;
        }

        #region <Property accessors>
        public string FullName
        {
            get { return fullname; }
            set { fullname = value; }
        }
        public string LoginName
        {
            get { return loginname; }
            set { loginname = value; }
        }
        public int UserID
        {
            get { return userid; }
            set { userid = value; }
        }
        public int Level
        {
            get { return level; }
            set { level = value; }
        }
        public DateTime LoginDateTime
        {
            get { return logindatetime; }
            set { logindatetime = value; islogin = (DateTime.MinValue.Equals(value)); }
        }
        public string Department
        {
            get { return department; }
            set { department = value; }
        }
        public bool IsOperUser
        {
            get { return _IsOperUser; }
            set { _IsOperUser = value; }
        }
        public bool IsLogin
        {
            get { return islogin; }
            set { islogin = value; }
        }
        public UserPermission Permission
        {
            get { return permission; }
            set { permission = value; }
        }
        #endregion
    }
    #endregion class userLogin

    public interface IPageLoadControl
    {
        void LoadCtrl(string WUCPageName);
        
    }

}
/// <summary>
/// This interface make control can perform function databind.
/// </summary>
public interface IContractControl
{

    //can add any type of parameter
     void GridDataBindA(string keys, string value);
     void GridDataBindA(ParameterCollection parms);
     //void GridDataBindA(Tbl_SpQueryStatusAllCriteria regFind);
     ParameterCollection FindParms
    {
        get;
        set;
    }
}
